package cn.hzking.gjmall.delegates.main;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fingdo.statelayout.StateLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.activitys.order.SureOrderActivity;
import cn.hzking.gjmall.adpters.car.ShopcartExpandableListViewAdapter;
import cn.hzking.gjmall.base.BaseDelegate;
import cn.hzking.gjmall.bean.DeleteSkuBean;
import cn.hzking.gjmall.bean.SureOrderBean;
import cn.hzking.gjmall.bean.car.entity.CarBean;
import cn.hzking.gjmall.bean.car.entity.CarSkuNumBean;
import cn.hzking.gjmall.bean.car.entity.CutOrderBean;
import cn.hzking.gjmall.net.RetrofitFactory;
import cn.hzking.gjmall.net.base.BaseObserver;
import cn.hzking.gjmall.utils.Logger;
import cn.hzking.gjmall.utils.OnClickEvent;
import cn.hzking.gjmall.utils.PriceFormatUtils;
import cn.hzking.gjmall.utils.SPUtils;
import cn.hzking.gjmall.utils.SwipeRefreshLayoutUtils;
import cn.hzking.gjmall.utils.UIUtils;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class CarDelegate extends BaseDelegate implements ShopcartExpandableListViewAdapter.CheckInterface, ShopcartExpandableListViewAdapter.ModifyCountInterface, View.OnClickListener {


    @Bind(R.id.car_edit)
    TextView carEdit; //编辑完成按钮
    @Bind(R.id.car_bar1)
    RelativeLayout carBar1;
    @Bind(R.id.car_allseclect)
    ImageView carAllseclect; //全选按钮
    @Bind(R.id.car_allprice)
    TextView carAllprice; //总共价格
    @Bind(R.id.tv_soujia)
    TextView tvSoujia;//售价文字
    @Bind(R.id.tv_youhui)
    TextView tvYouhui;//优惠文字
    @Bind(R.id.tv_topay)
    TextView toPay;//结算文字
    @Bind(R.id.car_topay)
    LinearLayout carTopay; //结算按钮
    @Bind(R.id.tv1_car)
    TextView textView1;//无关文字
    @Bind(R.id.car_buttom_ll)
    LinearLayout carButtomLl;//底部
    @Bind(R.id.exListView)
    ExpandableListView carRv;
    @Bind(R.id.refresh)
    SwipeRefreshLayout refresh;
    @Bind(R.id.statelayout)
    StateLayout statelayout;
    @Bind((R.id.car_view))
    View view1;//线
    private ShopcartExpandableListViewAdapter spAdapter;
    boolean isDNext = false;//拆分订单对话框是否能进行下步操作
    /*---------------数据集合----------------*/
    ArrayList<CarBean.DataBean.EffectBean.ActivityBean> groups = new ArrayList<>();// 组元素数据列表
    HashMap<Integer, List<CarBean.DataBean.EffectBean.ActItemsBean>> children = new HashMap<>();// 子元素数据列表
    /*--------------状态值------------------*/
    private int editState = 0;//0为显示文字编辑(结算状态), 1为显示文字完成(删除状态)
    private double totalPrice = 0.00;// 购买的商品总价
    private double oldPrice = 0.00;//原本的售价
    private double reducedPrice = 0.00;//优惠价格
    private boolean isAllSeceted = false;//是否全部选中
    private final int SHIXIAOZHUID = -100;
    private boolean isRefresh = false;

    public CarDelegate() {

    }


    @Override
    public Object setLayout() {
        return R.layout.fragment_car_delegate;
    }


    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        initEvents();
    }

    private void initEvents() {
        SwipeRefreshLayoutUtils.initRefreshLayout(refresh);
        EventBus.getDefault().register(this);
        spAdapter = new ShopcartExpandableListViewAdapter(_mActivity);
        spAdapter.setCheckInterface(this);// 关键步骤1,设置复选框接口
        spAdapter.setModifyCountInterface(this);// 关键步骤2,设置数量增减接口
        carRv.setAdapter(spAdapter);
        carRv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    View lastVisibleItemView = carRv.getChildAt(carRv.getChildCount() - 1);
                    if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == carRv.getHeight()) {
                        view1.setVisibility(View.VISIBLE);
                    } else {
                        view1.setVisibility(View.GONE);
                    }
                }

                //但是第一个条目的时候让刷新可用,反之不可用
                if (firstVisibleItem == 0) {
                    refresh.setEnabled(true);
                }
                else{
                    refresh.setEnabled(false);
                }
        }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                //do nothing
            }

        });
        carEdit.setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                if (editState == 0) {//显示编辑,不能编辑状态
                    editIng();

                } else if (editState == 1) {//显示完成,正在编辑状态
                    completeEdit();
                }
            }
        });

        //点击group的点击事件
        carRv.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                UIUtils.showToast(_mActivity, groupPosition + "", Toast.LENGTH_SHORT);
                return true;
            }
        });
        //点击child的点击事件
        carRv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
               // Toast.makeText(_mActivity, "点击子布局事件" + groupPosition + "---" + childPosition, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        //长按点击事件
        carRv.setOnItemLongClickListener(new QuickWayListener());
        carAllseclect.setOnClickListener(this);
        carTopay.setOnClickListener(this);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                clearAllPrice();
                clearAll();
                isAllSeceted = false;
                carAllseclect.setSelected(false);
                getNetData(_mActivity,false,true);
            }
        });


    }


    //完成编辑(结算)
    private void completeEdit() {
        carEdit.setText("编辑");
        toPay.setText("去结算");
        hideAddCutRl(false);
        carAllseclect.setSelected(false);
        doCheckAll();
        editState = 0;
        textView1.setVisibility(View.VISIBLE);
        carAllprice.setVisibility(View.VISIBLE);
        tvSoujia.setVisibility(View.VISIBLE);
        tvYouhui.setVisibility(View.VISIBLE);
    }

    //正在编辑
    private void editIng() {
        carEdit.setText("完成");
        toPay.setText("删除");
        hideAddCutRl(true);
        carAllseclect.setSelected(false);
        doCheckAll();
        editState = 1;
        textView1.setVisibility(View.INVISIBLE);
        carAllprice.setVisibility(View.INVISIBLE);
        tvSoujia.setVisibility(View.INVISIBLE);
        tvYouhui.setVisibility(View.INVISIBLE);


    }


    //显示和隐藏加减布局
    private void hideAddCutRl(boolean isHide) {
        for (int i = 0; i < groups.size(); i++) {
            List<CarBean.DataBean.EffectBean.ActItemsBean> actItemsBeans = children.get(groups.get(i).getmId());
            for (int j = 0; j < actItemsBeans.size(); j++) {
                actItemsBeans.get(j).setHideNumText(isHide);
            }

        }
        spAdapter.notifyDataSetChanged();


    }

    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给底部的textView进行数据填充
     */
    private void calculate() {
        totalPrice = 0.00;//需要支付价格
        oldPrice = 0.00; //原始总价格
        reducedPrice = 0.00; //优惠价格
        for (int i = 0; i < groups.size(); i++) {
            double activityPrice = 0.00;
            CarBean.DataBean.EffectBean.ActivityBean group = groups.get(i);
            List<CarBean.DataBean.EffectBean.ActItemsBean> childs = children.get(group.getmId());
            for (int j = 0; j < childs.size(); j++) {
                CarBean.DataBean.EffectBean.ActItemsBean product = childs.get(j);
                if (product.isChoosed()) {
                    if (!product.isShiXiao()) {//没有失效
                        oldPrice = oldPrice + product.getNumber() * product.getPrice();
                        if (product.isWhetherActivite()) {
                            if (System.currentTimeMillis() > product.getGmtStart() && System.currentTimeMillis() < product.getGmtStop()) {
                                reducedPrice += (product.getPrice() - product.getSnapupPrice()) * product.getNumber();
                            }
                        }

                    }
                }
            }
            //n元选活动
            if (group.getDefId() == 1) {
                if (group.getSelectNum() >= Integer.parseInt(group.getConditionNum())) {//选中的大于活动所需要的数量
                    ArrayList<Double> prices = new ArrayList<>();
                    for (int k = 0; k < childs.size(); k++) {
                        prices.add(childs.get(k).getPrice());
                    }
                    Collections.sort(prices, new Comparator<Double>() {
                        @Override
                        public int compare(Double o1, Double o2) {
                            return o2.compareTo(o1);
                        }
                    });

                    for (int g = 0; g < prices.size(); g++) {
                        if (g < Integer.parseInt(group.getConditionNum())) {
                            activityPrice += prices.get(g);
                        } else {
                            break;
                        }
                    }
                    double v = Double.parseDouble(group.getConditionPrice());
                    reducedPrice = reducedPrice + (activityPrice - v);

                }

            }

            // todo 满减活动

        }


        String oldPriceString = PriceFormatUtils.valueFormatWithTwo(String.valueOf(oldPrice));
        String reducedPriceString = PriceFormatUtils.valueFormatWithTwo(String.valueOf(reducedPrice));
        totalPrice = oldPrice - reducedPrice;
        String totalPriceString = PriceFormatUtils.valueFormatWithTwo(String.valueOf(totalPrice));
        carAllprice.setText("￥" + totalPriceString);
        tvSoujia.setText(String.format(Locale.CHINA, "售价%s", oldPriceString));
        tvYouhui.setText(String.format(Locale.CHINA, "优惠%s", reducedPriceString));


    }

    //检查是否组全部选中
    private boolean isAllCheck() {

        for (CarBean.DataBean.EffectBean.ActivityBean group : groups) {
            if (!group.isChoosed())
                return false;

        }

        return true;
    }


    /**
     * 全选与反选
     */
    private void doCheckAll() {
        for (int i = 0; i < groups.size(); i++) {
            groups.get(i).setChoosed(carAllseclect.isSelected());
            CarBean.DataBean.EffectBean.ActivityBean group = groups.get(i);
            List<CarBean.DataBean.EffectBean.ActItemsBean> childs = children.get(group.getmId());
            for (int j = 0; j < childs.size(); j++) {
                childs.get(j).setChoosed(carAllseclect.isSelected());
            }
            if (group.getDefId() == 1) {//1:是表示N元选活动
                if (carAllseclect.isSelected()) {
                    group.setSelectNum(childs.size());
                } else {
                    group.setSelectNum(0);
                }
            }
        }
        spAdapter.notifyDataSetChanged();
        calculate();
    }

    /**
     * 全选之前的初始化
     */
    private void longClickInit() {
        for (int i = 0; i < groups.size(); i++) {
            groups.get(i).setChoosed(false);
            CarBean.DataBean.EffectBean.ActivityBean group = groups.get(i);
            List<CarBean.DataBean.EffectBean.ActItemsBean> childs = children.get(group.getmId());
            for (int j = 0; j < childs.size(); j++) {
                childs.get(j).setChoosed(false);
            }
            if (group.getDefId() == 1) {
                group.setSelectNum(0);
            }
        }
        spAdapter.notifyDataSetChanged();
        calculate();
    }

    /**
     * 删除操作<br>
     * 1.不要边遍历边删除，容易出现数组越界的情况<br>
     * 2.现将要删除的对象放进相应的列表容器中，待遍历完后，以removeAll的方式进行删除
     */
    protected void doDelete() {
        List<CarBean.DataBean.EffectBean.ActivityBean> toBeDeleteGroups = new ArrayList<>();// 待删除的组元素列表
        for (int i = 0; i < groups.size(); i++) {
            CarBean.DataBean.EffectBean.ActivityBean group = groups.get(i);
            if (group.isChoosed()) {
                toBeDeleteGroups.add(group);
                children.remove(group.getmId());
                continue;

            }
            List<CarBean.DataBean.EffectBean.ActItemsBean> toBeDeleteProducts = new ArrayList<>();// 待删除的子元素列表
            List<CarBean.DataBean.EffectBean.ActItemsBean> childs = children.get(group.getmId());
            for (int j = 0; j < childs.size(); j++) {
                if (childs.get(j).isChoosed()) {
                    toBeDeleteProducts.add(childs.get(j));
                }
            }
            childs.removeAll(toBeDeleteProducts);
            children.put(group.getmId(), childs);


        }

        groups.removeAll(toBeDeleteGroups);
        spAdapter.setNewData(groups, children);
        if (groups.size() == 0) {
            showButtom(true);
            isRefresh = true;
            View view = View.inflate(_mActivity, R.layout.layout_statelayout_car_empty, null);
            view.findViewById(R.id.car_empty_btn).setOnClickListener(new OnClickEvent() {
                @Override
                public void singleClick(View v) {
                    EventBus.getDefault().post("goHome");
                }
            });
            statelayout.showCustomView(view);
        }
        calculate();
    }

    //点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.car_allseclect://全选按钮
                if (isAllSeceted) {//已经全选,点击变成全不选
                    clearAll();

                } else {//没有全选,点击变成全选
                    selcetAll();
                }
                doCheckAll();
                break;
            case R.id.car_topay:
                if (editState == 0) {//结算
                   /* isAllSeceted = false;
                    carAllseclect.setSelected(true);*/
                    settleMent();


                } else if (editState == 1) {//删除
                    isAllSeceted = false;
                    carAllseclect.setSelected(false);
                    ArrayList chooseSkus = getChooseSku();
                    deleteOneSku(chooseSkus,0,0,null,false);
                   // doDelete();

                }
                break;
        }

    }

    //结算
    private void settleMent(){
        int baoshuiSku = 0 ;
        ArrayList<Integer> skuIds = new ArrayList<>();
        ArrayList<Integer> nums = new ArrayList<>();

        for (int i = 0; i < groups.size(); i++) {
            List<CarBean.DataBean.EffectBean.ActItemsBean> actItemsBeans = children.get(groups.get(i).getmId());
            for (int j = 0; j < actItemsBeans.size(); j++) {
                CarBean.DataBean.EffectBean.ActItemsBean actItemsBean = actItemsBeans.get(j);
                if(actItemsBean.isChoosed()){
                    if(!actItemsBean.isShiXiao()){//没有失效
                        skuIds.add(actItemsBean.getId());
                        nums.add(actItemsBean.getNumber());
                        if("保税".equals(actItemsBean.getSellpattern())){//是保税
                            baoshuiSku = baoshuiSku+1;
                            if(baoshuiSku >1 && totalPrice >2000){
                                // 保税商品的数量大于一件,并且保税商品的总价格大于200元时不能购买,弹出对话框提示
                                createTishiDialog().show();
                                return;
                            }

                        }

                    }
                }
            }
        }
        //拆分自营保税和其他支付单接口
        cutOrder(skuIds,nums);


    }

    //得到被选中的sku的id的list
    private ArrayList getChooseSku(){
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < groups.size(); i++) {
            List<CarBean.DataBean.EffectBean.ActItemsBean> actItemsBeans = children.get(groups.get(i).getmId());
            for (int j = 0; j < actItemsBeans.size(); j++) {
                if(actItemsBeans.get(j).isChoosed()){
                    list.add(actItemsBeans.get(j).getId());
                }
            }
        }
        return  list;
    }
    private void selcetAll() {
        carAllseclect.setSelected(true);//选中
        isAllSeceted = true;
    }


    private void clearAll() {
        carAllseclect.setSelected(false);//选中
        isAllSeceted = false;
    }

    @Override
    public void checkGroup(int groupPosition, boolean isChecked) {


    }

    //子条目选中监听
    @Override
    public void checkChild(int groupPosition, int childPosition, boolean isChecked) {
        boolean allChildSameState = true;// 判断改组下面的所有子元素是否是同一种状态
        CarBean.DataBean.EffectBean.ActivityBean group = groups.get(groupPosition);
        List<CarBean.DataBean.EffectBean.ActItemsBean> childs = children.get(group.getmId());
        childs.get(childPosition).setChoosed(isChecked);
        for (int i = 0; i < childs.size(); i++) {
            if (childs.get(i).isChoosed() != isChecked) {
                allChildSameState = false;
                break;
            }
        }
        if (group.getDefId() == 1) {//N元选活动
            if (isChecked) {
                group.setSelectNum(group.getSelectNum() + 1);
            } else {
                group.setSelectNum(group.getSelectNum() - 1);
            }

        }
        //todo 满减活动 group自定义价格字段，选中则价格累加，否则则减少，根据此累加价格和服务器满减价格相比较，去显示Group的title文字
        if (allChildSameState) {
            group.setChoosed(isChecked);// 如果所有子元素状态相同，那么对应的组元素被设为这种统一状态
        } else {
            group.setChoosed(false);// 否则，组元素一律设置为未选中状态
        }

        if (isAllCheck()) {
            isAllSeceted = true;
            carAllseclect.setSelected(true);
        } else {
            isAllSeceted = false;
            carAllseclect.setSelected(false);
        }
        spAdapter.notifyDataSetChanged();
        calculate();


    }


    //点击加号按钮
    @Override
    public void doIncrease(int groupPosition, int childPosition, View showCountView, boolean isChecked) {
        setSkuNum(groupPosition, childPosition, showCountView, isChecked, true);
      /*  CarBean.DataBean.EffectBean.ActItemsBean product = (CarBean.DataBean.EffectBean.ActItemsBean) spAdapter.getChild(groupPosition, childPosition);
        int currentCount = product.getNumber();
        currentCount++;
        if (currentCount > product.getCurrentNumber()) {//但加了购物车的数量大于库存时
            currentCount = product.getCurrentNumber();
        }
        product.setNumber(currentCount);
        ((TextView) showCountView).setText(currentCount + "");
        spAdapter.notifyDataSetChanged();
        calculate();*/

    }

    //点击减号按钮
    @Override
    public void doDecrease(int groupPosition, int childPosition, View showCountView, boolean isChecked) {
        setSkuNum(groupPosition, childPosition, showCountView, isChecked, false);
       /* CarBean.DataBean.EffectBean.ActItemsBean product = (CarBean.DataBean.EffectBean.ActItemsBean) spAdapter.getChild(groupPosition, childPosition);
        int currentCount = product.getNumber();
        if (currentCount == 1) {
            return;
        }
        currentCount--;
        product.setNumber(currentCount);
        ((TextView) showCountView).setText(currentCount + "");

        spAdapter.notifyDataSetChanged();
        calculate();*/

    }

    //长按监听器
    public class QuickWayListener implements AdapterView.OnItemLongClickListener {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View view,
                                       int pos, long id) {
            int groupPos = (Integer) view.getTag(R.id.group); //参数值是在setTag时使用的对应资源id号
            int childPos = (Integer) view.getTag(R.id.child);
            if (childPos == -1) {//长按的是父项
                //根据groupPos判断你长按的是哪个父项，做相应处理（弹框等）
                Toast.makeText(_mActivity, "父布局" + groupPos, Toast.LENGTH_SHORT).show();
            } else {
                //deleteOneItem(groupPos, childPos);
                if (editState == 0) {
                    Dialog dialog = createDialog(groupPos, childPos);
                    dialog.show();
                }
            }
            return true;
        }

    }

    //长按删除一条商品信息
    private void deleteOneItem(int groupPos, int childPos) {
        longClickInit();
        //根据groupPos及childPos判断你长按的是哪个父项下的哪个子项，然后做相应处理。
        CarBean.DataBean.EffectBean.ActItemsBean child = (CarBean.DataBean.EffectBean.ActItemsBean) spAdapter.getChild(groupPos, childPos);
        CarBean.DataBean.EffectBean.ActivityBean group = (CarBean.DataBean.EffectBean.ActivityBean) spAdapter.getGroup(groupPos);
        int childrenCount = spAdapter.getChildrenCount(groupPos);

        if (childrenCount == 1) {
            group.setChoosed(true);
        } else {
            child.setChoosed(true);
        }


        doDelete();

    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        getNetData(_mActivity, true, false);

    }

    //从服务端得到数据
    private void getNetData(Activity activity, boolean isShowDialog, boolean isCancel) {
        RetrofitFactory.getInstant().API().getCarData()
                .compose(this.<CarBean>setThread())
                .subscribe(new BaseObserver<CarBean>(activity, isShowDialog, isCancel) {
                    @Override
                    protected void onSuccees(CarBean carBean) throws Exception {
                        showButtom(false);
                        isRefresh = false;
                        if(refresh != null){
                            refresh.setRefreshing(false);
                        }
                        initGoodList(carBean);

                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        isRefresh = true;
                        if(refresh != null){
                            refresh.setRefreshing(false);
                        }
                          showButtom(true);
                            View customView = LayoutInflater.from(mActivity).inflate(R.layout.layout_statelayout_custom_error1, null);
                            statelayout.showCustomView(customView);



                    }
                });
    }

    //提取数据,初始化数据
    private void initGoodList(CarBean carBean) {
        statelayout.showContentView();
        groups.clear();
        children.clear();
        List<CarBean.DataBean.EffectBean> effect = carBean.getData().getEffect();//有效商品列表
        List<CarBean.DataBean.UneffectBean> uneffect = carBean.getData().getUneffect();
        int effectSize = effect.size();
        int unEffectSize = uneffect.size();
        if (effectSize == 0 && unEffectSize == 0) {//如果有效商品和失效商品都没有
            showButtom(true);
            isRefresh = true;
            View view = View.inflate(_mActivity, R.layout.layout_statelayout_car_empty, null);
            view.findViewById(R.id.car_empty_btn).setOnClickListener(new OnClickEvent() {
                @Override
                public void singleClick(View v) {
                    EventBus.getDefault().post("goHome");
                }
            });
            statelayout.showCustomView(view);
            return;
        }
        //给组列表添加数据
        if (effectSize != 0) {//没有失效
            for (int i = 0; i < effectSize; i++) {
                CarBean.DataBean.EffectBean.ActivityBean activity = effect.get(i).getActivity();
                activity.setmId(i + 1);
                groups.add(activity);
                children.put(activity.getmId(), effect.get(i).getActItems());

            }
        }
        if (unEffectSize != 0) {//失效
            ArrayList<CarBean.DataBean.EffectBean.ActItemsBean> list = new ArrayList<>();
            CarBean.DataBean.EffectBean.ActivityBean activityBean = new CarBean.DataBean.EffectBean.ActivityBean(SHIXIAOZHUID);
            groups.add(activityBean);
            for (int i = 0; i < unEffectSize; i++) {
                CarBean.DataBean.UneffectBean uneffectBean = uneffect.get(i);
                CarBean.DataBean.EffectBean.ActItemsBean actItemsBean = new CarBean.DataBean.EffectBean.ActItemsBean();
                actItemsBean.setShiXiao(true);
                actItemsBean.setInvalidReason(uneffectBean.getInvalidReason());
                actItemsBean.setAvecostPrice(uneffectBean.getAvecostPrice());
                actItemsBean.setCashRebateLevel(uneffectBean.getCashRebateLevel());
                actItemsBean.setCurrentNumber(uneffectBean.getCurrentNumber());
                actItemsBean.setCurrentPrice(uneffectBean.getCurrentPrice());
                actItemsBean.setGmtDisplay(uneffectBean.getGmtDisplay());
                actItemsBean.setGmtStart(uneffectBean.getGmtStart());
                actItemsBean.setGmtStop(uneffectBean.getGmtStop());
                actItemsBean.setGrossWeight(uneffectBean.getGrossWeight());
                actItemsBean.setId(uneffectBean.getId());
                actItemsBean.setIsUnderStock(uneffectBean.isIsUnderStock());
                actItemsBean.setItemId(uneffectBean.getItemId());
                actItemsBean.setMaxPurchase(uneffectBean.getMaxPurchase());
                actItemsBean.setMinPurchase(uneffectBean.getMinPurchase());
                actItemsBean.setNetWeight(uneffectBean.getNetWeight());
                actItemsBean.setNumber(uneffectBean.getNumber());
                actItemsBean.setOriginalPrice(uneffectBean.getOriginalPrice());
                actItemsBean.setPrice(uneffectBean.getPrice());
                actItemsBean.setAvecostPrice(uneffectBean.getAvecostPrice());
                actItemsBean.setRealMaxPurchase(uneffectBean.getRealMaxPurchase());
                actItemsBean.setRealMinPurchase(uneffectBean.getRealMinPurchase());
                actItemsBean.setRealPrice(uneffectBean.getRealPrice());
                actItemsBean.setRealStockNumber(uneffectBean.getRealStockNumber());
                actItemsBean.setRestrictionNumber(uneffectBean.getRestrictionNumber());
                actItemsBean.setSellpattern(uneffectBean.getSellpattern());
                actItemsBean.setSkucode(uneffectBean.getSkucode());
                actItemsBean.setSkuname(uneffectBean.getSkuname());
                actItemsBean.setSnapupNumber(uneffectBean.getSnapupNumber());
                actItemsBean.setSnapupPrice(uneffectBean.getSnapupPrice());
                actItemsBean.setStockNumber(uneffectBean.getStockNumber());
                actItemsBean.setTaxCategoryId(uneffectBean.getTaxCategoryId());
                actItemsBean.setTaxMiniprice(uneffectBean.getTaxMiniprice());
                actItemsBean.setTaxRate(uneffectBean.getTaxRate());
                actItemsBean.setTaxation(uneffectBean.getTaxation());
                actItemsBean.setThumbImageUrl(uneffectBean.getThumbImageUrl());
                actItemsBean.setTime(uneffectBean.getTime());
                actItemsBean.setTitle(uneffectBean.getTitle());
                actItemsBean.setWarehouseId(uneffectBean.getWarehouseId());
                actItemsBean.setWhetherActivite(uneffectBean.isWhetherActivite());

                list.add(actItemsBean);
            }
            children.put(SHIXIAOZHUID, list);

        }

        spAdapter.setNewData(groups, children);
        for (int i = 0; i < spAdapter.getGroupCount(); i++) {
            carRv.expandGroup(i);// 关键步骤3,初始化时，将ExpandableListView以展开的方式呈现
        }

    }

    public Dialog createDialog(final int groupPos, final int childPos) {
        LayoutInflater inflater = LayoutInflater.from(_mActivity);
        View v = inflater.inflate(R.layout.dialog_car_delete, null);// 得到加载view
        final Dialog customDialog = new Dialog(_mActivity, R.style.dialog_1);// 创建自定义样式dialog
        customDialog.setCanceledOnTouchOutside(false);
        customDialog.setCancelable(false);
        customDialog.setContentView(v);
        v.findViewById(R.id.delete).setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                ArrayList<Integer> list = new ArrayList<>();
                int id = children.get(groups.get(groupPos).getmId()).get(childPos).getId();
                list.add(id);
                deleteOneSku(list,groupPos,childPos,customDialog,true);

            }
        });
        v.findViewById(R.id.cancel).setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                customDialog.dismiss();
            }
        });

        return customDialog;
    }

    //自营保税商品不能超过2000元对话框
    public Dialog createTishiDialog() {
        LayoutInflater inflater = LayoutInflater.from(_mActivity);
        View v = inflater.inflate(R.layout.dialog_car_tishi, null);// 得到加载view
        final Dialog customDialog = new Dialog(_mActivity, R.style.dialog_1);// 创建自定义样式dialog
        customDialog.setCanceledOnTouchOutside(false);
        customDialog.setCancelable(false);
        customDialog.setContentView(v);
        v.findViewById(R.id.sure).setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
               customDialog.dismiss();

            }
        });


        return customDialog;
    }



    //商品个数加减接口
    private void setSkuNum(int groupPosition, int childPosition, final View showCountView, boolean isChecked, final boolean isAdd) {
        final CarBean.DataBean.EffectBean.ActItemsBean product = (CarBean.DataBean.EffectBean.ActItemsBean) spAdapter.getChild(groupPosition, childPosition);
        int currentCount = product.getNumber();
        int id = product.getId();
        if (isAdd) {
            currentCount++;
        } else {
            currentCount--;
        }
        showCountView.setTag(currentCount);
        HashMap<String, String> parms = new HashMap<>();
        parms.put("userId", "");
        parms.put("itemSkuId", String.valueOf(String.valueOf(id)));
        parms.put("number", String.valueOf(currentCount));

        RetrofitFactory.getInstant().API()
                .getSkuCarNumber(parms)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CarSkuNumBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CarSkuNumBean value) {
                        if ("success".equals(value.getResult())) {//请求成功
                            Integer tag = (Integer) showCountView.getTag();
                            if(tag >0 && tag < product.getCurrentNumber()) {
                                product.setNumber(tag);
                                ((TextView) showCountView).setText(String.valueOf(tag));
                                spAdapter.notifyDataSetChanged();
                                calculate();
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    //购物车sku删除接口

    private void deleteOneSku(ArrayList<Integer> list, final int groupPos, final int childPos, final Dialog customDialog, final boolean isDeleteOne) {
        String skuId = "";
        for (int i = 0; i < list.size(); i++) {
            if(i == 0) {
                skuId = skuId + String.valueOf(list.get(i));
            }else {
                skuId = skuId+","+list.get(i);
            }
        }
        RetrofitFactory.getInstant().API()
                .deleteSku(skuId)
                .compose(this.<DeleteSkuBean>setThread())
                .subscribe(new Observer<DeleteSkuBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(DeleteSkuBean value) {
                        if ("success".equals(value.getResult())) {
                            if(isDeleteOne) {//删除一条数据时
                                deleteOneItem(groupPos, childPos);
                                if (customDialog != null) {
                                    customDialog.dismiss();
                                }
                            }else {//删除多条数据
                                doDelete();
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        if(customDialog != null) {
                            customDialog.dismiss();
                        }
                        UIUtils.showToast(_mActivity,"删除失败",Toast.LENGTH_SHORT);

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //拆分订单
    private void cutOrder(ArrayList<Integer> skuIds ,ArrayList<Integer> nums){
        HashMap<String, String> parms = new HashMap<>();
        String skuIdsString = "";
        String numsString = "";
        for (int i = 0; i < skuIds.size(); i++) {
            if(i == 0){
                skuIdsString = skuIdsString+skuIds.get(i);
            }else {
                skuIdsString = skuIdsString+","+skuIds.get(i);
            }

        }
        for (int i = 0; i < nums.size(); i++) {
            if(i == 0){
                numsString = numsString+nums.get(i);
            }else {
                numsString = numsString+","+nums.get(i);
            }

        }
        parms.put("itemSkuIds",skuIdsString);
        parms.put("numbers",numsString);
        RetrofitFactory.getInstant().API()
                .getCutOrderData(parms)
                .compose(this.<CutOrderBean>setThread())
                .subscribe(new BaseObserver<CutOrderBean>(_mActivity,true,true) {
                    @Override
                    protected void onSuccees(CutOrderBean cutOrderBean) throws Exception {
                        CutOrderBean.DataBean data = cutOrderBean.getData();
                        int bondSum = data.getBondSum();//保税订单个数
                        int commonSum = data.getCommonSum();//非保税订单个数
                        String bondSkuIds = data.getBondSkuIds();
                        String bondNumbers = data.getBondNumbers();
                        String commonSkuIds = data.getCommonSkuIds();
                        String commonNumbers = data.getCommonNumbers();
                        if(bondSum >0 && commonSum >0){//需要拆分订单
                            //显示对话框
                            cutOrderDialog(bondSkuIds,bondNumbers,bondSum,commonSkuIds,commonNumbers,commonSum).show();
                        }else {
                        //    getSureOrderData(bondSkuIds,bondNumbers,bondSum,commonSkuIds,commonNumbers,commonSum);
                            if(bondSum > 0){//自营保税
                                getSureOrderData(true,bondSkuIds,bondNumbers,bondSum,commonSkuIds,commonNumbers,commonSum);
                            }else {
                                getSureOrderData(false,bondSkuIds,bondNumbers,bondSum,commonSkuIds,commonNumbers,commonSum);
                            }

                        }


                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {

                    }
                });

    }

    //先请求确认订单数据
    private void getSureOrderData(final boolean isBond, final String bondSkuIds, final String bondNumbers, int bondSum, final String commonSkuIds, final String commonNumbers, int commonSum) {
        HashMap<String, String> parms = new HashMap<>();
        if(isBond){//是自营商品
            parms.put("itemSkuIds",bondSkuIds);
            parms.put("numbers",bondNumbers);
        }else {
            parms.put("itemSkuIds",commonSkuIds);
            parms.put("numbers",commonNumbers);
        }
        parms.put("addressId", String.valueOf(SPUtils.getAddressId(_mActivity)));
        RetrofitFactory.getInstant().API().getSureOrderData(parms)
                .compose(this.<SureOrderBean>setThread())
                .subscribe(new BaseObserver<SureOrderBean>(_mActivity,false,false) {
                    @Override
                    protected void onSuccees(SureOrderBean sureOrderBean) throws Exception {
                        if(isBond){
                            Intent intent = new Intent(_mActivity, SureOrderActivity.class);
                            intent.putExtra("itemSkuIds",bondSkuIds);
                            intent.putExtra("numbers",bondNumbers);
                            intent.putExtra("isBond",true);
                            startActivity(intent);
                        }else {
                            Intent intent = new Intent(_mActivity, SureOrderActivity.class);
                            intent.putExtra("itemSkuIds",commonSkuIds);
                            intent.putExtra("numbers",commonNumbers);
                            intent.putExtra("isBond",false);
                            startActivity(intent);
                        }

                    }

                    @Override
                    protected void onCodeError(SureOrderBean sureOrderBean) throws Exception {
                        super.onCodeError(sureOrderBean);
                        UIUtils.showToast(mActivity,sureOrderBean.getErrorMsg(),Toast.LENGTH_SHORT);
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        Logger.e(e.getMessage());
                        UIUtils.showToast(mActivity,getString(R.string.request_error),Toast.LENGTH_SHORT);

                    }
                });



    }


    //拆分订单对话框
    public Dialog cutOrderDialog(final String bondSkuIds, final String  bondNums, final int bondSum, final String commonSkuIds, final String commonNumbers , final int commonSum) {
        LayoutInflater inflater = LayoutInflater.from(_mActivity);
        View v = inflater.inflate(R.layout.dialog_car_caiorder, null);// 得到加载view
        final ImageView baoshuiCheck = v.findViewById(R.id.baoshui_check);
        final ImageView notBaoShui = v.findViewById(R.id.notbaoshui_check);
        TextView baoshuiText = v.findViewById(R.id.baoshui_text);
        TextView notBaoShuiText = v.findViewById(R.id.notbaoshui_text);
        baoshuiText.setText(String.format(Locale.CHINA,"自营保税商品共%d件",bondSum));
        notBaoShuiText.setText(String.format(Locale.CHINA,"其他商品共%d件",commonSum));
        final Dialog customDialog = new Dialog(_mActivity, R.style.dialog_1);// 创建自定义样式dialog
        customDialog.setContentView(v);
        customDialog.setCanceledOnTouchOutside(false);
        customDialog.setCancelable(false);
        final Intent intent = new Intent(_mActivity, SureOrderActivity.class);

        //非保税
        notBaoShui.setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                baoshuiCheck.setSelected(false);
                notBaoShui.setSelected(true);
               // getSureOrderData(false,bondSkuIds,bondNums,bondSum,commonSkuIds,commonNumbers,commonSum);

                intent.putExtra("itemSkuIds",commonSkuIds);
                intent.putExtra("numbers",commonNumbers);
                intent.putExtra("nextSkuIds",bondSkuIds);
                intent.putExtra("nextNumbers",bondNums);
                intent.putExtra("isBond",false);
                isDNext = true;
            }
        });
        //保税
        baoshuiCheck.setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                baoshuiCheck.setSelected(true);
                notBaoShui.setSelected(false);
               // getSureOrderData(true,bondSkuIds,bondNums,bondSum,commonSkuIds,commonNumbers,commonSum);
                intent.putExtra("itemSkuIds",bondSkuIds);
                intent.putExtra("numbers",bondNums);
                intent.putExtra("nextSkuIds",commonSkuIds);
                intent.putExtra("nextNumbers",commonNumbers);
                intent.putExtra("isBond",true);
                isDNext = true;

            }
        });
        //结算
        v.findViewById(R.id.car_pay).setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                if(isDNext) {
                    startActivity(intent);
                    customDialog.dismiss();
                    isDNext = false;
                }

            }
        });
        //返回
        v.findViewById(R.id.car_back).setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                customDialog.dismiss();
                isDNext = false;
            }
        });

        return customDialog;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String code){
        if ("goCar".equals(code) || "错误返回".equals(code)) {//跳转到购物车,重新请求数据  或者是确认订单页面库存不足等返回
            clearAllPrice();
            clearAll();
            getNetData(_mActivity,false,true);
        }


    }

    private void clearAllPrice(){
        totalPrice = 0.00;//需要支付价格
        oldPrice = 0.00; //原始总价格
        reducedPrice = 0.00; //优惠价格
        carAllprice.setText("￥" + "0.00");
        tvSoujia.setText(String.format(Locale.CHINA, "售价%s", "0.00"));
        tvYouhui.setText(String.format(Locale.CHINA, "优惠%s", "0.00"));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden && isRefresh){
            getNetData(_mActivity,false,true);
        }
    }

    //隐藏显示底部
    private void showButtom(boolean isHidde){
        if(isHidde){
            carButtomLl.setVisibility(View.GONE);
            view1.setVisibility(View.GONE);

        }else {
            carButtomLl.setVisibility(View.VISIBLE);
            view1.setVisibility(View.VISIBLE);
        }
    }
}
